package blog.spring.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import blog.core.exception.FormParamErrorException;
import blog.spring.db.entity.SysUser;
import blog.spring.db.entity.User;
import blog.spring.db.service.IUserService;
import blog.spring.web.util.CookieUtils;
import blog.spring.web.util.CookieUtils.LoginType;

@Controller
@RequestMapping("/user")
public class UserController extends BlogController {

	public UserController() {
		super("type");
		// TODO Auto-generated constructor stub
	}

	@Resource
	private IUserService userService;

	/************ 注册 *************/
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "user/register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(User user) {
		SysUser sy = new SysUser();
		user.setSysUser(sy);
		try {
			userService.addSysUser(user);
		} catch (FormParamErrorException e) {
			e.printStackTrace();
			return "redirect:/user/register";
		}
		return redirect("/user/login");
	}

	/************ 登陆 *************/
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "user/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest req, HttpServletResponse resp,
			User user) {

		User tempUser = null;
		try {
			tempUser = userService
					.login(user.getUserName(), user.getPassWord());
		} catch (FormParamErrorException e) {
			e.printStackTrace();
			return "user/login";
		}
		if (tempUser != null) {
			CookieUtils.setLoginCookie(req, resp, tempUser, LoginType.LOGIN);
		}
		return redirectIndex();
	}

	/************ 注销 *************/
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest req, HttpServletResponse resp) {
		CookieUtils.setLoginCookie(req, resp, null, LoginType.LOGOUT);
		return redirectIndex();
	}
}
